<template>
  <view>
    <view class="box-head">
      <PickerHeader ref="refUniMallHead" @change="tabChange"></PickerHeader>
    </view>
    <scroll-view scroll-y="true" style="height: 84.5vh;">
      <view class="box-list">
        <template v-for="item in currentData" :key="item.id">
          <view class="box-list-item" :class="[
            item.children && item.children.length ? 'box-list-item-dept-icon' : '',
            item.type === 'user' ? 'box-list-item-user' : 'box-list-item-dept'
          ]" @click="handelClickItem(item)">
            <radio @click="handelClickItem(item)" v-if="item.type === 'user'" v-show="entry == 'component'"
              style="transform: scale(0.8)" :checked="setChecked(item)" />
            <radio @click="handelClickItem(item)" v-if="item.type === 'dept' && type == 'dept'"
              v-show="entry == 'component'" style="transform: scale(0.8)" :checked="setChecked(item)" />
            <view class="box-list-item-dept-pic" v-if="item.type === 'dept'">
              <image src="@/static/dept-icon.png"></image>
            </view>
            <view class="box-list-item-user-pic" v-else>
              <!-- <image v-if="item.avatar" :src="item.avatar" mode="aspectFill"></image> -->
              <!-- image-local url-->
              <image-local v-if="item.avatar" :id="item.id" :url="item.avatar" radius="10rpx" width="40px"
                height="50px"></image-local>
              <text v-else>{{ getUserName(item.name) }}</text>
            </view>
            <view class="box-list-item-right">
              <view class="box-list-item-text">{{ item.name }} {{ item.children && item.children.length > 0 ?
                `（${item.children.length}）` : '' }}</view>
              <!-- 角色标签 职务 -->
              <view class="box-list-item-user-tag" v-if="item.type === 'user' && item.tag && item.type.length > 0">
                <text v-for="(tag, tagIndex) in item.tag">{{ tag }}</text>
              </view>
              <!-- 部门切换下级 -->
              <view class="box-list-item-user-tag tag-c" v-if="item.type === 'dept'"
                @click.stop="handelClickItem(item, true)">
                <text style="font-size: 30rpx;">下级</text>
              </view>
            </view>
          </view>
        </template>
      </view>
    </scroll-view>

    <view class="select-container" v-show="entry == 'component'">
      <view class="select-left">
        <text>已选择（{{ selection.length }}）:</text>
      </view>
      <!-- 单选 -->
      <view v-if="!multiple" class="scrollContainer">
        <view v-for="item in selection" :key="item.id" class="single-item">
          <text>{{ item.name }}</text>
        </view>
      </view>
      <!-- 多选左右滚动 -->
      <scroll-view v-else class="scrollContainer" scroll-x>
        <view style="display: flex;" @click="show = true">
          <view v-for="item in selection" :key="item.id" class="select-item">
            <!-- 替换本地 -->
            <!-- <image v-if="item.avatar" mode="aspectFill" :src="item.avatar"></image> -->
            // #ifdef APP-PLUS
            <image-local v-if="item.avatar" :id="item.id" :url="item.avatar" radius="6rpx" width="72rpx"
              height="72rpx"></image-local>
            <text v-else>{{ item.name }}</text>
            // #endif

            // #ifdef H5
            <view class="h5-image-wrapper" v-if="item.avatar">
              <image :src="item.avatar" :style="{ width: '72rpx', height: '72rpx', borderRadius: '6rpx' }"
                @error="handleH5ImageError(item)" mode="aspectFill" />
              <text v-if="item.showTextInstead" class="fallback-text">{{ getFallbackName(item.name) }}</text>
            </view>
            <text v-else>{{ item.name }}</text>
            // #endif
          </view>
        </view>
      </scroll-view>
      <view class="select-right">
        <up-button @click="submit" :customStyle="{ border: 'none', width: '92rpx', height: '52rpx' }"
          :disabled="selection.length == 0" type="primary" text="确定"></up-button>
      </view>
    </view>
    <!-- 弹出框 -->
    <up-popup :show="show" @close="show = fasle" :customStyle="{ height: '56vh' }">
      <view class="popup-header">
        <view @click="show = false">
          <up-icon :size="18" bold name="close"></up-icon>
        </view>
        <view style="font-weight: 500;">已选择({{ selection.length }})</view>
        <view @click="show = false">确定</view>
      </view>
      <view class="popup-content">
        <view v-for="item in selection" :key="item.id" class="select-item">
          <view style="display: flex; align-items: center;">
            <!-- 替换本地 -->
            <!-- <image v-if="item.avatar" :src="item.avatar" mode="aspectFill"></image> -->
            <image-local v-if="item.avatar" :id="item.id" :url="item.avatar" radius="6rpx" width="72rpx"
              height="72rpx"></image-local>
            <text v-else>{{ item.name }}</text>
            <view>{{ item.name }}</view>
          </view>
          <view>
            <up-button :customStyle="{ border: 'none' }" plain size="mini" :hairline="false" @click="removeAndAdd(item)"
              text="移除"></up-button>
          </view>
        </view>
      </view>
    </up-popup>
  </view>
</template>

<script>
import base from '@/apis/cloud/base';
import ImageLocal from '@/components/image-local/image-local.vue';
import { SysAvatar } from '@/utils/sql/avatar';
import PickerHeader from '@/components/watermarkCamera/members-header.vue';

export default {
	name:'OrgMembers',
	components: {
		PickerHeader,
		ImageLocal
	},
	props: {
		// page页面使用 component组件使用
		entry: {
			type: String,
			default: 'page'
		},
		type: {
			type: String,
			default: 'user'
		},
		multiple: {
			type: Boolean,
			default: true
		}
	},
	data () {
		return {
			show: false,
			currentData: [],
			defaultHeadList: { name: '工程管理中心', id: '33' },
			dataList: [{
				id: 1,
				name: "江苏绿港",
				type: "dept",
				person_num: 400
			}],
			selection: []
		};
	},
	mounted () {
		this.init();
	},
	methods: {
		handleH5ImageError (item) {
			this.$set(item, 'showTextInstead', true); // 添加响应式字段
		},
		getFallbackName (name) {
			if (!name) return '';
			if (name.length <= 2) return name;
			return name.slice(-2); // 取最后两个字
		},
		submit () {
			this.$emit('ok', this.selection);
		},
		isEntry () {
			if (this.entry == 'page') return false;
		},
		async init (id) {
			if (Object.keys(this.defaultHeadList).length > 0) {
				this.$refs.refUniMallHead.addTab(this.defaultHeadList);
			}

			// 创建 sys_avatar
			//#ifdef APP-PLUS
			await SysAvatar.init();
			// #endif

			this.getCurrentData(33);
		},
		// 是否选中
		setChecked (event) {
			const findIndex = this.selection.findIndex(item => item.id == event.id)
			if (findIndex != -1) {
				return true
			} else {
				return false
			}
		},
		// 顶部部门切换
		tabChange (obj) {
			this.defaultHeadList = obj;
			this.getCurrentData(obj.id, true);
		},

		handelClickItem (item, change) {
			// 切换部门 获取数据
			if ((item.type === 'dept' && this.type != 'dept') || change) {
				console.log("123====", item.type)
				this.getCurrentData(item.id);
				this.defaultHeadList = item;
				this.$refs.refUniMallHead.addTab({ name: item.name, id: item.id });
				return
			}
			this.$emit('change', item);
			this.removeAndAdd(item);
		},
		removeAndAdd (item) {
			// 选中
			const findIndex = this.selection.findIndex(i => item.id == i.id);
			if (findIndex != -1) {
				this.selection.splice(findIndex, 1);
			} else {
				if (this.multiple) {
					this.selection.push(item);
					const arr = [...new Set(this.selection)];
					this.selection = arr;
				} else {
					this.selection = [item];
				}
			}
		},
		// 名称处理
		getUserName (name) {
			if (name.length === 0) {
				return '';
			} else if (name.length <= 2) {
				return name;
			} else if (name.length >= 3) {
				return name.substring(name.length - 2);
			}
		},
		// 获取数据
		async getCurrentData (id, topTabChange) {
			if (id !== this.defaultHeadList.id || topTabChange) {
				const msg = await base.getGroupData({ deptId: id, type: this.type });
				this.currentData = msg.data;
			}
		},
	}
};
</script>

<style lang="scss" scoped>
.h5-image-wrapper {
  position: relative;
  display: inline-block;
}

.fallback-text {
  position: absolute;
  top: 0;
  left: 0;
  right: 0;
  bottom: 0;
  display: flex;
  align-items: center;
  justify-content: center;
  font-size: 20rpx;
  color: white;
  background-color: rgba(0, 0, 0, 0.3); // 可选背景色增强可读性
  text-align: center;
}

.box-head {
  position: fixed;
  left: 0px;
  width: 100%;
  height: 48px;
  background: #ffffff;
  padding-left: 17px;
  box-sizing: border-box;
  overflow-y: hidden;
  z-index: 999;
}

.box-list {
  padding-top: 52px;

  .box-list-item {
    position: relative;
    height: 60px;
    display: flex;
    align-items: center;
    padding: 0 14px;
    box-sizing: border-box;
    background: #ffffff;
    margin-bottom: 1px;

    &:active {
      background: #f2f3f4;
    }

    &:last-child {
      margin-bottom: 0px;
    }

    .box-list-item-dept-pic {
      width: 40px;
      height: 40px;
      background: rgba(55, 127, 255, 0.1);
      border-radius: 10rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 14px;
      overflow: hidden;

      image {
        width: 20px;
        height: 20px;
      }
    }

    .box-list-item-user-pic {
      width: 40px;
      height: 40px;
      background: #377fff;
      border-radius: 10rpx;
      display: flex;
      align-items: center;
      justify-content: center;
      margin-right: 14px;
      overflow: hidden;

      image {
        width: 40px;
        height: 40px;
      }

      text {
        color: #ffffff;
        font-size: 12px;
      }
    }

    .box-list-item-right {
      display: flex;
      align-items: center;
      justify-content: space-between;
      flex: 1;
    }

    .box-list-item-text {
      color: #333333;
      font-size: 16px;
    }

    .box-list-item-user-tag {
      text {
        box-sizing: border-box;
        border-radius: 8px;
        padding: 4px 8px;
        font-size: 10px;
        margin-left: 5px;

        &:first-child {
          margin-left: 0px;
        }

        &:nth-child(1) {
          background: rgba(49, 210, 144, 0.05);
          color: #31d290;
        }

        &:nth-child(2) {
          background: rgba(55, 127, 255, 0.05);
          color: #377fff;
        }
      }
    }

    .tag-c {
      text {
        color: #377fff !important;
      }
    }

    &.box-list-item-dept-icon {
      &::after {
        content: '';
        position: absolute;
        width: 5px;
        height: 10px;
        top: 26px;
        right: 15px;
        background: url(@/static/more.png) no-repeat;
      }
    }
  }
}

.select-container {
  position: fixed;
  box-sizing: border-box;
  bottom: 0;
  padding: 30rpx 20rpx;
  width: 100vw;
  display: flex;
  align-items: center;
  background-color: #fff;
  border-top: 1px solid #E1E3E5;

  .scrollContainer {
    width: 60%;
    display: flex;
  }

  .select-left {
    font-size: 26rpx;
    width: 25%;
  }

  .select-right {
    width: 10%;
  }
}

.single-item {
  text {
    font-size: 32rpx;
  }
}

.select-item {
  display: flex;
  align-items: center;
  justify-content: space-between;

  image {
    display: inline-block;
    width: 60rpx;
    height: 60rpx;
    border-radius: 6rpx;
    margin: 0 4rpx;
  }

  text {
    display: inline-block;
    width: 60rpx;
    height: 60rpx;
    text-align: center;
    font-size: 20rpx;
    line-height: 60rpx;
    border-radius: 6rpx;
    background-color: #2979ff;
    color: #fff;
    margin: 0 4rpx;
  }
}

.popup-header {
  display: flex;
  justify-content: space-between;
  align-items: center;
  font-size: 32rpx;
  padding: 30rpx;
}

.popup-content {
  .select-item {
    margin-bottom: 10rpx;
    border-bottom: 1px solid #E1E3E5;
    padding: 14rpx 20rpx;

    image {
      width: 72rpx;
      height: 72rpx;
    }

    text {
      width: 72rpx;
      height: 72rpx;
      font-size: 24rpx;
      line-height: 72rpx;
    }

    view {
      font-size: 28rpx;
      margin-left: 24rpx;
    }
  }

  .select-item:last-child {
    border: none !important;
  }
}
</style>
